/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：AlipayreturnServlet   
 * 类描述： 阿里支付回调接口  
 * 创建人：zhangl  
 * 创建时间：2016年12月10日 上午11:41:43   
 * 修改人：zhangl   
 * 修改时间：2016年12月10日 上午11:41:43   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.util.AlipayNotify;
import com.lst.model.MstOrder;
import com.lst.model.OrderDetail;
import com.lst.model.vo.MstOrderVo;
import com.lst.service.MstOrderService;
import com.lst.service.MstTransactionService;
import com.lst.service.OrderDetailService;

/**
 * @ClassName: AlipayreturnServlet
 * @Description:阿里支付通知接口
 * @author zhangl
 * @date 2016年12月10日 上午11:41:43
 * 
 */
public class AlipayreturnServlet extends BaseServlet {

    /**
     * @Fields serialVersionUID
     */
    private static final long serialVersionUID = 1L;

    private MstOrderService mstOrderService = ctx
	    .getBean(MstOrderService.class);

    private OrderDetailService orderDetailService = ctx
	    .getBean(OrderDetailService.class);

    private MstTransactionService mstTransactionService = ctx
	    .getBean(MstTransactionService.class);

    @Override
    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {

	Date startDate = new Date();
	logger.info("AlipayreturnServlet doPost begin: " + startDate);

	try {

	    // 获取支付宝POST过来反馈信息
	    Map<String, String> params = new HashMap<String, String>();
	    Map<String, String[]> requestParams = request.getParameterMap();
	    for (Iterator<String> iter = requestParams.keySet().iterator(); iter
		    .hasNext();) {
		String name = (String) iter.next();
		String[] values = (String[]) requestParams.get(name);
		String valueStr = "";
		for (int i = 0; i < values.length; i++) {
		    valueStr = (i == values.length - 1) ? valueStr + values[i]
			    : valueStr + values[i] + ",";
		}

		// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
		logger.info("notify_url key-value : " + name
			+ "-----------------" + valueStr);
		// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
		// "UTF-8");
		params.put(name, valueStr);
	    }

	    String result = mstTransactionService.insertByAli(params);

	    logger.info("transaction history result: " + result);

	    // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
	    // 商户订单号
	    String tradeno = new String(request.getParameter("out_trade_no")
		    .getBytes("ISO-8859-1"), "UTF-8");

	    // 支付宝交易号
	    String alitradno = new String(request.getParameter("trade_no")
		    .getBytes("ISO-8859-1"), "UTF-8");

	    logger.info("notify_url 流水交易号: " + tradeno);

	    // 交易状态
	    String trade_status = new String(request.getParameter(
		    "trade_status").getBytes("ISO-8859-1"), "UTF-8");

	    // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

	    response.setContentType("text/html;charset=utf-8");
	    PrintWriter out = response.getWriter();

	    boolean flag = AlipayNotify.verify(params);

	    // if (flag) {// 验证成功

	    MstOrderVo ordervo = mstOrderService.selectOrderByTradeNo(tradeno);
	    Integer oid = ordervo.getId();
	    MstOrder o = new MstOrder();
	    o.setId(oid);
	    o.setAlipaytradeno(alitradno);
	    logger.info("插入阿里流水号：orderid = " + oid + "alitradeno =" + alitradno);
	    // 插入阿里流水号
	    mstOrderService.updateByPrimaryKeySelective(o);
	    if (trade_status.equals("TRADE_SUCCESS")
		    || trade_status.equals("TRADE_FINISHED")) {

		// 如果为代付款
		if (ordervo.getOrderStatus() == 27) {
		    OrderDetail od = new OrderDetail();
		    od.setId(ordervo.getOdid());
		    od.setOrderstatus(234);
		    orderDetailService.updateByPrimaryKeySelective(od);
		    logger.info("修改订单状态为待参与  orderdetailid="
			    + ordervo.getOdid());
		}
	    }

	    out.println("success");
	    /*
	     * } else {// 验证失败 out.println("fail"); }
	     */

	    logger.info("dec flag: " + flag);
	} catch (Exception e) {

	    logger.error("doPost error: ", e);
	}
    }

}
